package ch.sv7.tool.dbmanager.db.fix;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import ch.sv7.tool.dbmanager.db.SchemaElement;
import ch.sv7.tool.dbmanager.db.dialect.Dialect;
import ch.sv7.tool.dbmanager.db.dialect.DialectException;


/**
 * TODO: Document me!
 *
 * @author svt
 *
 */
public class GroupedSchemaFix extends AbstractSchemaFix implements SchemaFix {

	//private static final Logger log = Logger.getLogger(GroupedSchemaFix.class);
	
	private List fixes = new ArrayList();
	private int action;
	private int priority;
	private String description;
	private SchemaElement actionTarget;

	/**
	 * @param action
	 * @param priority
	 * @param description
	 */
	public GroupedSchemaFix(SchemaElement actionTarget, int action, int priority, String description) {
		super();
		this.action = action;
		this.priority = priority;
		this.description = description;
		this.actionTarget = actionTarget;
	}

	public int getAction() {
		return action;
	}

	public SchemaElement getActionTarget() {
		return actionTarget;
	}

	public void addFix(SchemaFix fix){
		fixes.add(fix);
	}
	
	public void addFixes(List fixes){
		this.fixes.addAll(fixes);
	}
	
	/*
	public void addFixedDifference(SchemaDifference difference) {
		super.addFixedDifference(difference);
		
		for (int i=0; i<fixes.size(); i++){
			SchemaFix fix = (SchemaFix)fixes.get(i);
			fix.addFixedDifference(difference);
		}
	}

	public void addFixedDifferences(List differences) {
		super.addFixedDifferences(differences);
		
		for (int i=0; i<fixes.size(); i++){
			SchemaFix fix = (SchemaFix)fixes.get(i);
			fix.addFixedDifferences(differences);
		}
	}
*/
	public void setDialect(Dialect dialect) {
		super.setDialect(dialect);
		for (int i=0; i<fixes.size(); i++){
			SchemaFix fix = (SchemaFix)fixes.get(i);
			fix.setDialect(dialect);
		}
	}

	public String getDescription() {
		return description;
	}

	public int getPriority() {
		return priority;
	}

	public String getSQLFix() throws DialectException {
		StringBuffer ddl = new StringBuffer();
		//StringBuffer fixesBuffer = new StringBuffer();
		ddl.append("\n-- Start of grouped Fix");
		/*
		Iterator iter = getFixedDifferences().iterator();
		while (iter.hasNext()){
			SchemaDifference diff = (SchemaDifference)iter.next();
			fixesBuffer.append("\n--   " + diff.getMessage());
		}
		ddl.append(fixesBuffer);
		*/
		for (int i=0; i<fixes.size(); i++){
			SchemaFix fix = (SchemaFix)fixes.get(i);
			ddl.append(fix.getSQLFix());
		}		
		ddl.append("-- End of grouped Fix");
		//ddl.append(fixesBuffer);
		return ddl.toString();
	}

	public void executeFixing(Connection conn) throws DialectException, SQLException {
		for (int i=0; i<fixes.size(); i++){
			SchemaFix fix = (SchemaFix)fixes.get(i);
			fix.executeFixing(conn);
		}			
	}

}
